<template>
  <view class="travel-request">
	  <hy-cell label="用车事由：">
	  	  <textarea
	  	    name=""
	  	    id=""
	  	    auto-height
			disabled
	  	    v-model="obj.reason"
	  	    placeholder="请输入用车事由"
	  	    style="text-align: right;"
	  	  ></textarea>
	  </hy-cell>
	  <hy-cell label="用车目的地：">
	    <input
	      type="text"
		  disabled
	      v-model="obj.destination"
	      placeholder="请输入用车目的地"
	      class="input-style"
	    />
	  </hy-cell>
	  <hy-cell label="用车人数：">
		  <input
		    type="text"
		    disabled
		    v-model="obj.peopleNum"
		    placeholder="请输入用车目的地"
		    class="input-style"
		  />
	  </hy-cell>
	  		  <hy-cell label="开始时间：">
	  		  	<input
	  		  	  type="text"
	  		  	  :value="obj.startTime"
	  		  	  disabled="true"
	  		  	  placeholder="请选择开始时间"
	  		  	  class="input-style"
	  		  	/>
	  		  </hy-cell>
	  		  <hy-cell label="结束时间：">
	  		  	<input
	  		  	  type="text"
	  		  	  :value="obj.overTime"
	  		  	  disabled="true"
	  		  	  placeholder="请选择结束时间"
	  		  	  class="input-style"
	  		  	/>
	  		  </hy-cell>
	  <hy-cell label="车量用途：">
	  	<input
	  	  type="text"
	  	  :value="getCarType"
	  	  disabled="true"
	  	  placeholder="请选择车量用途"
	  	  class="input-style"
	  	/>
	  </hy-cell>
	  <hy-cell v-if="obj.plateNumber" label="车牌号：">
	  	<input
	  	  type="text"
	  	  :value="obj.plateNumber"
	  	  disabled="true"
	  	  class="input-style"
	  	/>
	  </hy-cell>
	  <hy-cell v-if="obj.driverName" label="司机人员：">
	  	<input
	  	  type="text"
	  	  :value="obj.driverName"
	  	  disabled="true"
	  	  class="input-style"
	  	/>
	  </hy-cell>
	  <hy-cell v-if="obj.startMileage" label="开始里程(km)：">
	    <input
	      type="text"
	      v-model="obj.startMileage"
	  	disabled
	      class="input-style"
	    />
	  </hy-cell>
	  <hy-cell v-if="obj.overMileage" label="结束里程(km)：">
	    <input
	      type="text"
	      v-model="obj.overMileage"
	  	disabled
	      class="input-style"
	    />
	  </hy-cell>
	  <!-- <block v-if="!watchDetail&&approvalPersonShow&&!isEnd&&!obj.overMileage&&optionsList[0].taskName != '司机'"> -->
	  <block v-if="optionsList[0].taskName == '派车人'">
			<view style="height: 30rpx;background-color: #f8f8f8;"></view>
	  		<view class="title">用车派车单</view> 
			<!-- <picker mode="selector" range-key="plateNumber" :range="carList" @change="chooseCar"> -->
				<hy-cell label="车牌号：">
				  <!-- <input
					type="text"
					disabled
					v-model="plateNumber"
					placeholder="请选择车牌号"
					class="input-style"
				  /> -->
				  <cuihai-combox @input="valueChange('plateNumber')" placeholder="请输入并选择车牌号" style="text-align: right;" @getValue="getValue($event,'plateNumber')" :candidates="carList" isJSON keyName="plateNumber"></cuihai-combox>
				</hy-cell>
			<!-- </picker> -->
			
			<!-- <picker mode="selector" range-key="nickName" :range="carPeopleList" @change="chooseCarPeople"> -->
				<hy-cell label="司机人员：">
				  <!-- <input
					type="text"
					v-model="driverName"
					disabled
					placeholder="请选择司机人员"
					class="input-style"
				  /> -->
				  <cuihai-combox @input="valueChange('nickName')" placeholder="请输入并选择司机人员" style="text-align: right;" @getValue="getValue($event,'nickName')" :candidates="carPeopleList" isJSON keyName="nickName"></cuihai-combox>
				</hy-cell>
			<!-- </picker> -->
			
			<hy-cell v-if="plateNumber" label="开始里程(km)：">
			  <input
			    type="text"
			    v-model="startMileage"
				disabled
			    class="input-style"
			  />
			</hy-cell>
			<!-- <view  @click="DatePicker('startTime')">
			  <hy-cell label="开始时间：">
				<input
				  type="text"
				  :value="startTime"
				  disabled="true"
				  placeholder="请选择开始时间"
				  class="input-style"
				/>
			  </hy-cell>
			</view>
			<view  @click="DatePicker('overTime')">
			  <hy-cell label="结束时间：">
				<input
				  type="text"
				  :value="overTime"
				  disabled="true"
				  placeholder="请选择结束时间"
				  class="input-style"
				/>
			  </hy-cell>
			</view> -->
	  </block>
	  <block v-if="optionsList[0].taskName == '司机'">
		  <view style="height: 30rpx;background-color: #f8f8f8;"></view>
		  <view  @click="DatePicker('overTime')">
		    <hy-cell label="结束时间：">
		  	<input
		  	  type="text"
		  	  :value="overTime"
		  	  disabled="true"
		  	  placeholder="请选择结束时间"
		  	  class="input-style"
		  	/>
		    </hy-cell>
		  </view>
		  <hy-cell label="结束里程(km)：">
		    <input
		      type="text"
		      v-model="overMileage"
				placeholder="请输入结束里程"
		      class="input-style"
		    />
		  </hy-cell>
		</block>
		<block v-if="!isEnd&&obj.overMileage">
			<hy-cell label="驳回理由：">
			  <input
			    type="text"
			    v-model="comment"
							placeholder="如果驳回请输入驳回理由"
			    class="input-style"
			  />
			</hy-cell>
		</block>
	  <view style="height: 30rpx;background-color: #f8f8f8;"></view>
	  <view class="options" v-for="(item,index) in optionsList">
		  <view class="optionsTitle">{{item.taskName}}</view>
		  <view v-if="item.assigneeName">实际办理人：{{item.assigneeName}}</view>
		  <view v-if="item.assigneeName">办理人电话：{{item.phonenumber}}</view>
		  <view v-if="item.candidate">候选办理：{{item.candidate}}</view>
		  <view class="orange" v-if="item.comment&&item.comment.comment">内容：{{item.comment.comment}}</view>
		  <view>接收时间：{{item.createTime}}</view>
		  <view v-if="item.finishTime">办结时间：{{item.finishTime}}</view>
		  <view class="dot" :class="item.finishTime?'finishDot':''"></view>
	  </view>
      
	  <view v-if="!watchDetail" class="page-footer bottomBox">
		<button v-if="isEnd&&!obj.overMileage||!isEnd&&obj.overMileage||optionsList[0].taskName == '司机'" type="normal" @click="handleSave()">{{!isEnd&&obj.overMileage?'归档':'确认'}}</button>
		<button v-else type="normal" @click="handleSave()">确认</button>
		<button v-if="!isEnd&&obj.overMileage" type="normal" style="background-color: #ccc;color: #333;" @click="bohui()">驳回</button>
	  </view>
	  <view class="page-footer" v-else>
		<button type="normal" @click="back()">返回</button>
	  </view>
	  <view style="height: 120rpx;background-color: #f8f8f8;"></view>
	<mx-date-picker :show="showPicker" format="yyyy-mm-dd hh:ii:ss" type="datetime" :value="value" :show-tips="true" :begin-text="'入住'" :end-text="'离店'" :show-seconds="true" @confirm="ed" @cancel="ed" />
  </view>
</template>

<script>
import HyCell from "@/components/hy-cell";
import config from '@/config/config';
import MxDatePicker from "@/components/mx-datepicker/mx-datepicker.vue";
import cuihaiCombox from "@/components/cuihai-combox/cuihai-combox.vue";
import multipleSelect from "@/components/multiple-select";
import pickRegions from "@/components/pick-regions/pick-regions.vue";
export default {
  name: "travel-request",
  components: {
    "hy-cell": HyCell,
    "multiple-select": multipleSelect,
    "pick-regions": pickRegions,
	MxDatePicker,
	cuihaiCombox
  },
  data() {
    return {
		deptId:'',
		carUsing:[
			{value:1,label:'公司办公用车'},
			{value:2,label:'物流办公用车'},
			{value:3,label:'外出用车'},
			{value:4,label:'临时用车'},
			{value:0,label:'其他'},
		],
		obj:{
			purpose:1
		},
		comment:'',
		bohuilist:[],
		overMileage:'', // 结束里程
		isEnd:false,
		carList:[],
		carPeopleList:[],
		value:'',
		showPicker:false,
		plateNumber:'', // 车牌号
		driverName:'', // 司机人员
		driverId:'', // 司机id
		startMileage:'', // 开始里程
		// startTime:'', // 开始时间
		// overTime:'', // 结束时间
		approvalContent:'', // 审批内容
		watchDetail:true,
		taskId:'',
		name:'', //商店/内部名称
		title:'', //名称
		content:'', //内容
		phone:'', // 电话
		type:'', // 工单类型
	  approvalDepartment:'', // 审批部门
	  orderType:[], // 订单类型列表
	  department:[], // 部门列表
	  departmentPersonList:[], // 部门人员列表
	  approvalPerson:'', // 审批人
	  approvalPersonShow:false, // 审批人
	  optionsList:[]
    };
  },
  computed:{
	  getCarType(){
	  	return this.carUsing.filter(item=>{
	  		return this.obj.purpose ==item.value
	  	})[0].label
	  },
  },
  onLoad(options) {
	  config.verifyToken()
	if(options.approval){
		this.watchDetail = false
	}
	this.obj = uni.getStorageSync('taskDetail')
	this.getApprovalPersonStatus()
	this.getCarList()
	this.getRecords()
	this.getbohuiDetail()
  },
  onShow() {
	
  },
  methods: {
	  // 获取审核记录
	  getRecords(){
	  		this.$http
	  		  .get("/flowable/task/flowRecord",{
	  			  procInsId:this.obj.procInsId
	  		  })
	  		  .then((res) => {
	  			console.log(res,'审批记录')		    
	  			uni.hideLoading();
	  			if(this.obj.status == 3){
	  				this.optionsList = res.data.flowList.filter(item=>{
	  					return item.finishTime
	  				})
	  			} else {
	  				this.optionsList = res.data.flowList
	  			}
	  		  })
	  		  .catch((errorData) => {
	  		    uni.hideLoading();
	  		    console.log(errorData);
	  		  });
	  },
	  valueChange(type){
		 if(type =='plateNumber'){
		 	this.plateNumber = ''
		 	this.startMileage = ''
		 } else {
		 	this.driverName = ''
		 	this.driverId = ''
		 } 
	  },
	  getValue(e,type){
		if(type =='plateNumber'){
			let car = this.carList[e]
			this.plateNumber = car.plateNumber
			this.startMileage = car.mileage
		} else {
			let carPeople = this.carPeopleList[e]
			this.driverName = carPeople.nickName
			this.driverId = carPeople.userId
		}
	  },
	  getbohuiDetail(){
	  	uni.showLoading({
	  		title:'请稍等...'
	  	})
	  	this.$http
	  	  .post(
	  	    `/flowable/task/returnList`
	  	  ,{
	  					taskId:this.obj.taskId
	  				})
	  	  .then((res) => {
	  		  this.bohuilist = res.data.map(item=>{
	  			  item.descripition = item.name+'-'+item.owner
	  			  return item
	  		  })
	  			uni.hideLoading()
	  	    
	  	  })
	  	  .catch((errorData) => {
	  		 uni.hideLoading()
	  	  });
	  },
	  bohui(){
		  if(!this.comment){
			  this.showToast("请填写驳回理由");
			  return false;
		  }
		uni.showModal({
			content: '是否确认驳回？',
			showCancel: true,
			cancelText: '取消',
			confirmText: '确认',
			success: res => {
				if(res.confirm){
					// return
					uni.showLoading({
					  title: "加载中",
					});
					this.$http
					  .post("/flowable/task/return", {
						  taskId:this.obj.taskId,
						  comment:this.comment,
						  targetKey:this.bohuilist[0].id
					  })
					  .then(() => {
					    uni.hideLoading();
					    uni.showToast({
					      title: "提交成功",
					    });
					    setTimeout(() => {
							uni.setStorageSync('shenhe','1')
					      uni.navigateBack();
					    }, 1000);
					  })
					  .catch((errorData) => {
					    uni.hideLoading();
						uni.showToast({
						  title: errorData.msg,
						  duration:2000,
						  icon:'none'
						});
					    console.log(errorData);
					  });
				}
			}
		});
	  },
	  DatePicker(type){//显示
	  		  this.type = type;
	  		  this.showPicker = true;
	  		  this.value = this[type];
	  },
	  ed(e) {//选择
	  		  this.showPicker = false;
	  		  if(e) {
	  			  this[this.type] = e.value; 
	  			  //选择的值
	  			  console.log('value => '+ e.value);
	  			  //原始的Date对象
	  			  console.log('date => ' + e.date);
	  		  }
	  },
	  back(){
	  	uni.navigateBack()  
	  },
	  // 获取审核记录
	  getCarList(){
		this.$http
		  .get("/system/automobile/carList",{})
		  .then((res) => {
			console.log(res,'车牌列表')		    
			uni.hideLoading();
			this.carList = res.rows
		  })
		  .catch((errorData) => {
		    uni.hideLoading();
		    console.log(errorData);
		  });
	  },
	// 获取是否显示审批部门审批人
	getApprovalPersonStatus(){
		this.$http
		  .get("/system/user/profile")
		  .then((res) => {
			console.log(res,'是否显示审批人')		    
			uni.hideLoading();
			this.approvalPersonShow = res.data.showDriver
			this.isEnd = res.data.showOverMileage
			this.deptId = res.data.deptId
			this.getCarPeopleList()
		  })
		  .catch((errorData) => {
		    uni.hideLoading();
		    console.log(errorData);
		  });
	},
	// 获取工单类型
	getType(){
		this.$http
		  .get("/system/type/listAll")
		  .then((res) => {
			console.log(res)		    
			uni.hideLoading();
			this.orderType = res.data
		  })
		  .catch((errorData) => {
		    uni.hideLoading();
		    console.log(errorData);
		  });
	},
	// 选择司机
	chooseCarPeople(e){
		let carPeople = this.carPeopleList[e.detail.value]
		this.driverName = carPeople.nickName
		this.driverId = carPeople.userId
	},
	// 选择车
	chooseCar(e){
		let car = this.carList[e.detail.value]
		this.plateNumber = car.plateNumber
		this.startMileage = car.mileage
	},
	// 获取审批部门
	getCarPeopleList(){
		this.$http
		  // .get("/system/user/driverList?deptId="+this.deptId)
		  .get("/system/user/driverListAll")
		  .then((res) => {
			console.log(res,'司机列表')		    
			uni.hideLoading();
			this.carPeopleList = res.rows
		  })
		  .catch((errorData) => {
		    uni.hideLoading();
		    console.log(errorData);
		  });
	},
	// 选择审批部门
	chooseDepartment(e){
		if((this.approvalDepartment&&this.approvalDepartment.id!=this.department[e.detail.value].id)||!this.approvalDepartment){
			this.approvalDepartment = this.department[e.detail.value]
			this.getDepartmentPerson(this.approvalDepartment.id)
		}
	},
	// 获取部门人员
	getDepartmentPerson(id){
		this.$http
		  .get("/system/user/list?pageNum=1&pageSize=1000&deptId="+id)
		  .then((res) => {
			console.log(res,'部门人员')		    
			uni.hideLoading();
			this.approvalPerson = ''
			this.departmentPersonList = res.rows
		  })
		  .catch((errorData) => {
		    uni.hideLoading();
		    console.log(errorData);
		  });
	},
	// 选择审批人
	chooseApprovalPerson(e){
		this.approvalPerson = this.departmentPersonList[e.detail.value]
		console.log(this.approvalPerson)
	},
    showToast(txt, icon = "none") {
      uni.showToast({
        title: txt,
        duration: 1000,
        icon: icon,
      });
    },
    // 获取选择的出差人员
    confirm(data) {
      this.personnel = data.map((el) => el.label).join(",");
      this.personnelids = data.map((el) => el.value).join(",");
    },
    // 保存
    handleSave() {
      let valid = this.validate();

      if (valid) this.save();
    },
    // 必填项校验
    validate() {
      if (this.approvalPersonShow&&!this.isEnd&&!this.obj.overMileage&&this.optionsList[0].taskName != '司机') {
		  if (!this.plateNumber) {
			  let carCode = this.carList.filter(item=>{
				  return item.plateNumber == this.plateNumber
			  })
			  if(carCode.length == 0){
				  this.showToast("未查询到车牌号");
				  return false;
			  }
				this.showToast("请选择车牌号");
				return false;
		  }
		  if (!this.driverName) {
			this.showToast("请选择司机人员");
			return false;
		  }
      }
	  if(this.optionsList[0].taskName == '司机'){
		  if (!this.overTime) {
		  			this.showToast("请选择结束时间");
		  			return false;
		  }
		  if (!this.overMileage) {
		  			this.showToast("请填写结束里程");
		  			return false;
		  }
	  }
      return true;
    },
    // 提交申请
    save() {
      uni.showModal({
        title: "提示",
        content: this.isEnd?"是否确认？":"是否确认？",
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: "加载中",
            });
			let {
				procInsId, // 流程实例编号
				deployId,  // 流程定义编号
				taskId,// 流程任务编号
				procDefId,  // 流程编号
			} = this.obj
			let params = {
				plateNumber:this.plateNumber,
				driverName:this.driverName,
				driverId:this.driverId,
				overTime:this.overTime,
				overMileage:this.overMileage,
				startMileage:this.startMileage,
				returnTaskShow: false, // 是否展示回退表单
				delegateTaskShow: false, // 是否展示回退表单
				defaultTaskShow: true, // 默认处理
				sendUserShow: false, // 审批用户
				multiple: false,
				comment:'', // 意见内容
				procInsId, // 流程实例编号
				instanceId: procInsId, // 流程实例编号
				deployId,  // 流程定义编号
				taskId,// 流程任务编号
				procDefId,  // 流程编号
				vars: "",
				targetKey:"",
				// postType:this.optionsList[0].taskName == '司机'||this.optionsList[0].taskName == '审核员'||this.optionsList[0].taskName == '外出上级审核'||this.optionsList[0].taskName == '临时上级审核'||this.optionsList[0].taskName == '办公审核'||this.optionsList[0].taskName == '物流审核'||this.optionsList[0].taskName == '其他审核'?false:(!this.watchDetail&&this.approvalPersonShow&&!this.isEnd),//是否指派
				postUserId:''
			}
			console.log(params)
            this.$http
              .post("/flowable/task/complete", params)
              .then(() => {
                uni.hideLoading();
                uni.showToast({
                  title: "提交成功",
                });
                setTimeout(() => {
					uni.setStorageSync('shenhe','1')
                  uni.navigateBack();
                }, 1000);
              })
              .catch((errorData) => {
                uni.hideLoading();
				uni.showToast({
				  title: errorData.msg,
				  duration:2000,
				  icon:'none'
				});
                console.log(errorData);
              });
          }
        },
      });
    }
  },
};
</script>

<style lang="scss">
.travel-request {
  background: #fff;
  textarea {
    width: 100%;
    font-size: 28upx;
  }
  .input-style {
    text-align: right;
    font-size: 28upx;
  }
}
.options{
	padding: 10rpx 20rpx;
	border-bottom: 1rpx solid #CCC;
	position: relative;
	padding-left: 70rpx;
}
.dot{
	position: absolute;
	width: 30rpx;
	height: 30rpx;
	background-color: #B5BDBB;
	border-radius: 50%;
	left: 20rpx;
	top: 20rpx;
}
.optionsTitle{
	font-weight: 700;
	font-size: 34rpx;
	color: #333;
}
.finishDot{
	background-color: #60C13E;
}
.orange{
	color: orange;
}
.bottomBox{
	display: flex;
}
.bottomBox button{
	flex: 1;
}
.title{
	font-weight: 700;
	color: #333;
	padding: 30rpx;
}
</style>
